local extension = Package("rfenghou_chu")
extension.extensionName = "aaa_fenghou"

local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["rfenghou_chu"] = "彪楚",
}

local huanxuan = General:new(extension, "rfenghou__huanxuan", "chu", 4)

local rfenghou__pianyu = fk.CreateTriggerSkill{
  name = "rfenghou__pianyu",
  events = {fk.TurnStart},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      local last, next = player:getLastAlive(), player:getNextAlive()
      return last ~= next and table.contains({last, player, next}, target)
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local last, next = player:getLastAlive(), player:getNextAlive()
    local all = {last, player, next}
    local moves = {}
    for _, p in ipairs(all) do
      if p ~= target and not p:isNude() then
        local _, dat = room:askForUseActiveSkill(p, "rfenghou__pianyu_active", "#rfenghou__pianyu-give", false, nil, true)
        if not dat then
          dat = {cards = {p:getCardIds("he")[1]}, targets = {p:getNextAlive().id}}
        end
        table.insert(moves, {
          from = p.id,
          to = dat.targets[1],
          ids = dat.cards,
          toArea = Card.PlayerHand,
          moveReason = fk.ReasonGive,
          skillName = self.name,
          proposer = p.id,
          moveVisible = false,
        })
      end
    end
    if #moves > 0 then
      room:moveCards(table.unpack(moves))
    end
    local max_num = 0
    for _, p in ipairs(all) do
      max_num = math.max(max_num, p:getHandcardNum())
    end
    room:delay(600)
    local tos = table.filter(all, function(p) return p:getHandcardNum() == max_num end)
    if #tos == 1 then
      local to = tos[1]
      if not to.dead then
        room:doIndicate(player.id, {to.id})
        room:damage { from = player, to = to, damage = 1, skillName = self.name }
      end
    end
  end,
}
huanxuan:addSkill(rfenghou__pianyu)

local rfenghou__pianyu_active = fk.CreateActiveSkill{
  name = "rfenghou__pianyu_active",
  card_num = 1,
  target_num = 1,
  card_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  target_filter = function(self, to_select, selected)
    local to = Fk:currentRoom():getPlayerById(to_select)
    return #selected == 0 and Self.id ~= to_select and (to:getNextAlive() == Self or Self:getNextAlive() == to)
  end,
}
Fk:addSkill(rfenghou__pianyu_active)


local rfenghou__qiqing = fk.CreateViewAsSkill{
  name = "rfenghou__qiqing",
  mute = true,
  pattern = "nullification",
  prompt = "#rfenghou__qiqing",
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    local c = Fk:cloneCard("nullification")
    c.skillName = self.name
    return c
  end,
  before_use = function(self, player, use)
    local room = player.room
    use.unoffsetableList = table.map(room.players, Util.IdMapper)
    local tos = {}
    for _, p in ipairs(room:getAlivePlayers()) do
      if not table.contains(tos, p) then
        local next = p:getNextAlive()
        if next:getHandcardNum() > p:getHandcardNum() and next.seat > p.seat then
          table.insert(tos, p)
          table.insert(tos, next)
        end
      end
    end
    if #tos < 2 then return "" end
    local _, dat = room:askForUseActiveSkill(player, "rfenghou__qiqing_active", "#rfenghou__qiqing-choose", false, nil, true)
    if dat then
      tos = table.map(dat.targets, Util.Id2PlayerMapper)
    else
      tos = table.slice(tos, 1, 3)
    end
    table.sort(tos, function (a, b) return a.seat < b.seat end)
    player:broadcastSkillInvoke(self.name)
    room:notifySkillInvoked(player, self.name, "control", table.map(tos, Util.IdMapper))
    room:doIndicate(player.id, table.map(tos, Util.IdMapper))
    local num = #tos
    for i, p in ipairs(tos) do
      if num < 1 then break end
      if not p:isNude() then
        local isLast = i == #tos
        local cards = room:askForDiscard(p, isLast and num or 0, num, true, self.name, not isLast, ".", "#rfenghou__qiqing-discard:::"..num)
        if #cards == #tos then
          room:handleAddLoseSkills(player, "-"..self.name)
        end
        num = num - #cards
      end
    end
  end,
  enabled_at_response = function (self, player, response)
    return not response and table.find(Fk:currentRoom().alive_players, function (p)
      return p:getNextAlive():getHandcardNum() > p:getHandcardNum() and p:getNextAlive().seat > p.seat
    end)
  end,
}
huanxuan:addSkill(rfenghou__qiqing)

local rfenghou__qiqing_active = fk.CreateActiveSkill{
  name = "rfenghou__qiqing_active",
  card_num = 0,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    if #selected == 0 then return true end
    if #selected == 3 then return false end
    local last, to = Fk:currentRoom():getPlayerById(selected[#selected]), Fk:currentRoom():getPlayerById(to_select)
    return last:getNextAlive() == to and last:getHandcardNum() < to:getHandcardNum() and last.seat < to.seat
  end,
  feasible = function (self, selected)
    if #selected < 2 then return false end
    for i, pid in ipairs(selected) do
      local next = selected[i+1]
      if not next then return true end
      next = Fk:currentRoom():getPlayerById(next)
      local p = Fk:currentRoom():getPlayerById(pid)
      if not (p:getNextAlive() == next and p:getHandcardNum() < next:getHandcardNum() and p.seat < next.seat) then
        return false
      end
    end
  end,
}
Fk:addSkill(rfenghou__qiqing_active)

local rfenghou__huixi = fk.CreateTriggerSkill{
  name = "rfenghou__huixi$",
  events = {fk.AfterCardsMove},
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    if data.extra_data then
      local targets = data.extra_data.hcnm_becomeEmpty or {}
      local max = data.extra_data.hcnm_becomeOnlyMax
      if max then table.insertIfNeed(targets, max) end
      return table.find(targets, function (pid)
        local p = player.room:getPlayerById(pid)
        return p ~= player and not p.dead and p.kingdom == "chu" and p:getHandcardNum() ~= player:getHandcardNum()
        and not table.contains(player:getTableMark(self.name), p.id)
      end)
    end
  end,
  on_trigger = function (self, event, target, player, data)
    local targets = data.extra_data.hcnm_becomeEmpty or {}
    local max = data.extra_data.hcnm_becomeOnlyMax
    if max then table.insertIfNeed(targets, max) end
    player.room:sortPlayersByAction(targets)
    for _, pid in ipairs(targets) do
      if not player:hasSkill(self) then break end
      local p = player.room:getPlayerById(pid)
      if p ~= player and not p.dead and p.kingdom == "chu" and p:getHandcardNum() ~= player:getHandcardNum()
      and not table.contains(player:getTableMark(self.name), p.id) then
        self:doCost(event, p, player, data)
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local num = target:getHandcardNum() - player:getHandcardNum()
    self.cost_data = {tos = {target.id}}
    if num > 0 then
      return room:askForSkillInvoke(target, self.name, nil, "#rfenghou__huixi-draw::"..player.id..":"..math.min(2, num))
    else
      num = math.abs(num)
      return room:askForSkillInvoke(target, self.name, nil, "#rfenghou__huixi-discard::"..player.id..":"..math.min(2, num))
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:addTableMark(player, self.name, target.id)
    local num = target:getHandcardNum() - player:getHandcardNum()
    if num > 0 then
      player:drawCards(math.min(2, num), self.name)
    else
      num = math.abs(num)
      room:askForDiscard(player, num, num, false, self.name, false)
    end
  end,
}
huanxuan:addSkill(rfenghou__huixi)

Fk:loadTranslationTable{
  ["rfenghou__huanxuan"] = "桓玄",
  ["#rfenghou__huanxuan"] = "颇折蛟角",
  ["designer:rfenghou__huanxuan"] = "廷玉",
  ["illustrator:rfenghou__huanxuan"] = "啪啪三国",

  ["rfenghou__pianyu"] = "偏驭",
  [":rfenghou__pianyu"] = "你、你上家或你下家的回合开始时，你可以令另外二者同时选择交给其上家或下家一张牌。然后你对三者中手牌数唯一最大的角色造成1点伤害。",
  ["rfenghou__pianyu_active"] = "偏驭",
  ["#rfenghou__pianyu-give"] = "偏驭：请交给你上家或下家一张牌",

  ["rfenghou__qiqing"] = "岂倾",
  [":rfenghou__qiqing"] = "你可以令手牌数沿座位号递增的至多三名相邻角色共弃置等量张牌来视为使用一张不能被抵消的【无懈可击】；若有角色弃置全部所需牌，你失去此技能。",
  ["#rfenghou__qiqing"] = "岂倾：视为使用【无懈可击】，令手牌数递增的相邻角色依次弃牌",
  ["#rfenghou__qiqing-choose"] = "岂倾：选择2-3名手牌数递增的相邻角色，令他们弃牌",
  ["rfenghou__qiqing_active"] = "岂倾",
  ["#rfenghou__qiqing-discard"] = "岂倾：你需弃置至多 %arg 张牌",

  ["rfenghou__huixi"] = "虺玺",
  [":rfenghou__huixi"] = "主公技，每名楚势力角色限一次，其失去所有手牌或手牌数变为唯一最大后，可以令你将手牌数向其调整两张。",
  ["#rfenghou__huixi-discard"] = "虺玺：你可以令 %dest 弃置 %arg 张手牌",
  ["#rfenghou__huixi-draw"] = "虺玺：你可以令 %dest 摸 %arg 张牌",
}


return extension
